package com.woniuxy.permission.controller;


import com.woniu.commons.util.TokenUtil;
import com.woniu.zsd.commons.core.model.Result;
import com.woniuxy.permission.entity.Role;
import com.woniuxy.permission.form.AddRoleForm;
import com.woniuxy.permission.service.IRoleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
     * </p>
     *
 * @author author
 * @since 2025-05-13
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色管理模块")
public class RoleController {
    @Resource
    private IRoleService roleService;
    @Resource
    private TokenUtil tokenUtil;

    /**
     * 添加角色(仅有超管可以)
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加角色信息")
    public Result<String> addRole(@RequestBody AddRoleForm form, @RequestHeader("token") String token) throws Exception {

        Integer Id = tokenUtil.getAdminId(token);
        if (Id == 1) {
            roleService.addRole(form);
            return new Result<String>().setCode(200).setMsg("添加角色成功");
        } else {
            return new Result<String>().setCode(400).setMsg("权限不足,仅超级管理员可以添加角色信息");
        }
    }
    /**
     * 删除角色(仅有超管可以)
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除角色信息")
    public Result<String> deleteRole(@RequestParam Integer roleId, @RequestHeader("token") String token) throws Exception {
        Integer Id = tokenUtil.getAdminId(token);
        if (Id == 1) {
            roleService.deleteRole(roleId);
            return new Result<String>().setCode(200).setMsg("删除角色成功");
        } else {
            return new Result<String>().setCode(400).setMsg("权限不足,仅超级管理员可以删除角色信息");
        }
    }

    /*
     * 查看所有的角色信息(仅有超管可以)
     */
    @GetMapping("/getAll")
    @ApiOperation(value = "查看所有的角色信息")
    public Result<List<Role>> getAllRole(@RequestHeader("token") String token) throws Exception {
        Integer Id = tokenUtil.getAdminId(token);
        if (Id == 1) {
            List<Role> roles = (List<Role>) roleService.getAllRole();
            return new Result<List<Role>>().setCode(200).setData(roles);
        } else {
            return new Result<List<Role>>().setCode(400).setMsg("权限不足,仅超级管理员可以查看所有的角色信息");
        }
    }

    @PostMapping("/assign-resources")
    @ApiOperation("为角色分配资源")
    public Result<Void> assignResources(@RequestBody Map<String, Object> params) {
        Integer roleId = (Integer) params.get("roleId");
        @SuppressWarnings("unchecked")
        List<Integer> resourceIds = (List<Integer>) params.get("resourceIds");
        roleService.assignResources(roleId, resourceIds);
        return new Result<Void>().setCode(200).setMsg("资源分配成功");
    }


}
